<template>
  <div class="table">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-menu"></i>{{$route.name}}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div>
      <div class="handle-box">
        <el-dialog
          :title="title"
          :visible.sync="dialogFormVisible"
        >
          <el-form
            :model="addForm"
            :rules="rules"
            ref="addForm"
          >
            <el-form-item
              label="发布时间"
              :label-width="formLabelWidth"
            >
              <el-date-picker
                v-model="addForm.publicAt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="标题"
              :label-width="formLabelWidth"
              prop="title"
            >
              <el-input
                type="text"
                v-model="addForm.title"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="副标题"
              :label-width="formLabelWidth"
              prop="subTitle"
            >
              <el-input
                type="text"
                v-model="addForm.subTitle"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="简介"
              :label-width="formLabelWidth"
              prop="description"
            >
              <el-input
                type="text"
                v-model="addForm.description"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item
              label="广告位"
              prop="position"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="addForm.position"
                placeholder="请选择广告位"
              >
                <el-option
                  v-for="(item,index) in types"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item> -->

            <el-form-item
              label="内容"
              :label-width="formLabelWidth"
            >
              <!-- <el-input type="textarea" v-model="addForm.content" auto-complete="off"></el-input> -->
              <editor
                @input="htmlOutput"
                :htmlContent="addForm.content"
              ></editor>
            </el-form-item>
            <el-form-item
              label="专题分类"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="addForm.parentId"
                placeholder="请选择"
                @change="selectToGetChildTypeList()"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="专题分类"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="addForm.fTypeId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in childList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="来源"
              :label-width="formLabelWidth"
            >
              <el-input
                type="text"
                v-model="addForm.origin"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="作者"
              :label-width="formLabelWidth"
            >
              <el-input
                type="text"
                v-model="addForm.author"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="图片"
              :label-width="formLabelWidth"
            >
              <el-upload
                action=""
                class="avatar-uploader"
                ref="upload"
                accept="image/*"
                :http-request="upload"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                v-loading.fullscreen.lock="fullscreenLoading"
              >
                <img
                  v-if="imageUrl"
                  :src="imageUrl"
                  class="avatar"
                >
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="add"
            >确 定</el-button>
          </div>
        </el-dialog>
        <el-input
          v-model="select_word"
          placeholder="输入文章标题"
          class="search"
        ></el-input>
        <el-button
          type="primary"
          icon="search"
          @click="search"
        >搜索</el-button>
        <el-button
          type="primary"
          @click="addNews"
        >新增专题</el-button>
      </div>
      <div>
        <el-table
          :data="tableData"
          border
        >
          <el-table-column
            label="添加时间"
            prop="public_at"
            :formatter="timeFomatter"
          ></el-table-column>
          <el-table-column
            label="标题"
            prop="title"
          ></el-table-column>
          <el-table-column label="图片">
            <template
              slot-scope="scope"
              fixed
              prop="img_url"
            >
              <img
                :src="scope.row.img_url"
                width="100%"
                height="100%"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="简介"
            prop="description"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="所属子分类"
            prop="childName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="所属父分类"
            prop="parentName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="专题介绍"
            prop="content"
            show-overflow-tooltip
          ></el-table-column>
          <!-- <el-table-column
            label="广告位置"
            prop="origin"
            :formatter="positionFormatter"
          ></el-table-column> -->
          <el-table-column
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="put(scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                size="small"
                @click="del(scope.row)"
              >删除</el-button>
              <el-switch
                v-model="scope.row.state === 1 ? true : false"
                active-color="#13ce66"
                @change="switchChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="page.number"
          layout="total,  prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>

    </div>
  </div>
</template>
<script>
import { getAdTypes, getParentAdTypes, uploadFile, getChildTypeById, editThemeAd, getThemeAds, delThemeAd, editThemeAdState } from '../../server/getDate.js'
import { mapState, mapActions } from 'vuex'
import { dateFormatter, filterObj } from '../../utils/local.js'
import Editor from './../../components/common/Editor';
export default {
  data() {
    return {
      formLabelWidth: '120px',
      select_word: '',
      dialogFormVisible: false,
      fullscreenLoading: false,
      imageUrl: '',
      addForm: {},
      title: '',
      options: [{
        value: '0',
        label: '不推荐'
      }, {
        value: '1',
        label: '推荐'
      }],
      options1: [{
        value: '0',
        label: '不置顶'
      }, {
        value: '1',
        label: '置顶'
      }],
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        subTitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入简介', trigger: 'blur' }]
      },
      types: [{
        title: '头部',
        value: '0'
      }, {
        title: '上左',
        value: '1-1'
      }, {
        title: '上中',
        value: '1-2'
      }, {
        title: '上右',
        value: '1-3'
      }, {
        title: '中左',
        value: '2-1'
      }, {
        title: '中中',
        value: '2-2'
      }, {
        title: '中右',
        value: '2-3'
      }, {
        title: '中下左',
        value: '2-4'
      }, {
        title: '中下右',
        value: '2-5'
      }, {
        title: '下',
        value: '3'
      }],
    }
  },
  created() {
    this.getTypeList()
    this.getList(1)
    this.allThemeAdType()
  },
  components: {
    Editor
  },
  computed: mapState({
    tableData: state => state.ThemeAd.list,
    page: state => state.ThemeAd.page,
    typeList: state => state.ThemeAd.adTypeList,
    childList: state => state.ThemeAd.childTypeList
  }),
  methods: {
    ...mapActions(['saveThemeAdlist', 'saveAdTypes', 'saveChildTypeList', 'saveParentAdTypes']),
    allThemeAdType() {
      const params = {
        page: 1,
        pageSize: 100
      }
      getParentAdTypes({ ...params }).then(res => {
        if (res.code === '000000') {
          this.saveParentAdTypes(res)
        } else {
          this.$message.error(res.message)
        }
      }, err => this.$message.error(err.message))
    },
    handleCurrentChange(val) {
      this.getList(val)
    },
    beforeAvatarUpload(file) {
      this.fullscreenLoading = true
    },
    positionFormatter(row) {
      let position = ''
      this.types.some(item => {
        if (row.position === item.value) {
          position = item.title
          return true
        }
      })
      return position
    },
    upload(file) {
      this.fullscreenLoading = false
      let formData = new FormData()
      formData.append('fileName', file.file);
      formData.append('fileType', '1')
      uploadFile(formData, res => {
        this.fullscreenLoading = false
        if (res.code === '000000') {
          this.imageUrl = res.result.storageName
          this.addForm.imgUrl = this.imageUrl
        } else {
          this.$message.error(res.message)
        }
      }, err => {
        this.fullscreenLoading = false
      })
    },
    htmlOutput(html) {
      this.addForm.content = html
    },
    selectToGetChildTypeList() {
      console.log('bbbb', this.addForm.parentId)
      getChildTypeById({ 'id': this.addForm.parentId }).then(res => {
        if (res.code === '000000') {
          this.saveChildTypeList(res)
        }
      })
    },
    getTypeList() {
      const params = {
        page: 1,
        pageSize: 100
      }
      getAdTypes().then(res => {
        if (res.code === '000000') {
          this.saveAdTypes(res)
        } else {
          this.$message.error(res.message)
        }
      }, () => {
        this.$message.error('网络错误')
      })
    },
    getList(number) {
      const params = {
        page: number,
        pageSize: 10
      }
      if (this.select_word !== '') {
        params.searchKey = this.select_word
      }
      getThemeAds({ ...params }).then(res => {
        if (res.code === '000000') {
          this.saveThemeAdlist({
            ...res,
            number
          })
        } else {
          this.$message.error(res.message)
        }
      }, () => {
        this.$message.error('网络错误')
      })
    },
    search() {
      this.getList(this.page.number)
    },
    del(row) {
      this.$confirm('此操作将永久删除该名称, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delThemeAd({ id: row.id }).then(res => {
          if (res.code === '000000') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList(this.page.number)
          } else {
            this.$message.error(res.message)
          }
        }, err => this.$message.error(err.message))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    put(row) {
      console.log('row', row)
      this.title = '编辑专题广告'
      this.dialogFormVisible = true
      this.addForm = filterObj(row)
      if (row.public_at) {
        this.addForm.publicAt = dateFormatter(row.public_at).trim()
      }
      this.addForm.subTitle = row.sub_title
      this.imageUrl = this.addForm.img_url
      this.addForm.imgUrl = this.addForm.img_url
    },
    addNews() {
      this.dialogFormVisible = true
      this.addForm = {}
      this.title = '新增专题广告'
      this.imageUrl = ''
    },
    add() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          editThemeAd({ ...this.addForm }).then(res => {
            if (res.code === '000000') {
              this.$message.success('修改成功')
              this.getList(this.page.number)
            } else {
              this.$message.error(res.message)
            }
          }, () => {
            this.$message.error('网络错误')
          })
        }
      })
    },
    timeFomatter(row) {
      return dateFormatter(row.public_at)
    },
    reccFomatter(row) {
      return row.isRecommend === '0' ? '不推荐' : '推荐'
    },
    topFomatter(row) {
      return row.isTop === '0' ? '不置顶' : '置顶'
    },
    typeFomatter(row) {
      if (this.typeList.length === 0) {
        return '无'
      } else {
        let state = ''
        this.typeList.some(item => {
          if (item.id === row.fTypeId) {
            state = item.name
          }
        })
        return state
      }
    },
    switchChange(row) {
      editThemeAdState({
        id: row.id,
      }).then(res => {
        if (res.code === '000000') {
          this.$message.success('修改成功')
          this.getList(this.page.number)
        } else {
          this.$message.error(res.message)
        }
      }, () => {
        this.$message.error('网络错误')
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
